<style scoped lang="scss">
::v-deep .el-table td,
.el-table th {
  padding: 8px 0;
}
.dialog__body {
  background-color: #f3f3fa;
  border: 1px solid #bbbbbb;
  height: 68vh;
  overflow-y: auto;
  position: relative;
  display: flex;
  flex-direction: column;
}

.button-group {
  margin: 10px 0 0 10px;
  display: flex;
  justify-content: flex-end;

  &__info {
    margin-right: 10px;
  }
}

.tab-group {
  margin: 10px 0 0 0;
  height: 100%;

  .tab-group-top-table {
    // height: 50%;
    display: flex;
    margin: 0 10px;
  }

  .tab-group-bottom-table {
    // height: 50%;
    margin-top: 10px;
  }

  ::v-deep .el-tabs__nav-wrap {
    padding: 10px 10px 0 10px;
  }

  ::v-deep .el-tabs__header {
    margin: 0;
  }

  ::v-deep .el-tabs__nav-scroll {
    background-color: #ffffff;
    margin-bottom: 5px;
  }

  ::v-deep .el-tabs__nav {
    margin-left: 10px;
  }

  ::v-deep .el-tabs__nav-wrap:after {
    height: 0;
  }

  ::v-deep .el-tab-pane {
    padding: 0 10px;
  }

  .form {
    margin-top: 8px;
  }

  ::v-deep .el-form-item {
    margin-right: 0 !important;
  }

  ::v-deep .el-form-item__label {
    position: absolute;
  }

  ::v-deep .el-form-item__content {
    width: 30%;
  }

  ::v-deep .el-select,
  .el-input__inner {
    width: 100%;
  }
}

::v-deep .el-table th.is-leaf {
  background-color: #ffffff !important;
}

.button-group__footer {
  display: flex;
  flex-direction: row-reverse;
  margin: 10px 10px 10px 0;
  &__cancel {
    margin: 0 0 0 10px;
  }
}
.detect-downTable-row {
  cursor: pointer;
  color: #f63832;
}
.explain-block {
  div {
    font-weight: 700;
    font-size: 14px;
  }
  p {
    margin: 5px;
    font-size: 12px;
    text-indent: 2em;
  }
}
.border-table {
  height: 235px !important;
}
</style>
<template>
  <div class="dialog__body">
    <div class="button-group">
      <el-popover placement="right" width="200" trigger="click">
        <div class="explain-block">
          <div>功能：</div>
          <p>{{ explainData.funDescription }}</p>
          <div>输入端口：</div>
          <p>{{ explainData.inPort }}</p>
          <div>输出端口：</div>
          <p>{{ explainData.outPort }}</p>
          <div>参数：</div>
          <p>{{ explainData.functionName }}</p>
        </div>
        <mine-button
          slot="reference"
          type="primary"
          class="button-group__info"
          @click="getExplainInfo('attributecreate')"
          ><i class="iconfont icon-help-circle-line"></i>说明</mine-button
        >
      </el-popover>
    </div>
    <div class="tab-group">
      <div class="tab-group-top-table">
        <div style="width: 50%; padding-right: 5px">
          <!-- <div style="display: inline-block">函数</div>
          <el-input
            placeholder="请输入字段名"
            suffix-icon="el-icon-search"
            v-model="searchInput"
          >
          </el-input> -->
          <el-table
            class="table border-table"
            :data="leftTableData"
            style="width: 100%; display: inline-block"
            v-loading="loading"
            :height="tableHeight"
            ref="multipleTable"
            @row-click="leftTableRowClick"
            :row-style="{ height: 30 + 'px' }"
          >
            <el-table-column
              prop="optCode"
              label="函数名称"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="optName"
              label="函数类型"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="description"
              label="返回类型"
              show-overflow-tooltip
            >
            </el-table-column>
          </el-table>
        </div>
        <div style="width: 50%">
          <!-- <div style="display: inline-block">选择列</div>
          <el-input
            placeholder="请输入字段名"
            suffix-icon="el-icon-search"
            v-model="searchInput"
          >
          </el-input> -->
          <el-table
            class="table border-table"
            :data="rightTableData"
            style="width: 100%; display: inline-block"
            v-loading="loading"
            :height="tableHeight"
            ref="multipleTable"
            @row-click="rightTableRowClick"
          >
            <el-table-column prop="name" label="字段名" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="type" label="类型" show-overflow-tooltip>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="tab-group-bottom-table">
        <div>
          <span style="margin-left: 10px; margin-bottom: 10px">新属性</span>
        </div>
        <!-- :height="tableHeight" -->
        <el-table
          :height="downTableHeight"
          class="table"
          :data="downTableData"
          style="width: 100%"
          v-loading="loading"
          ref="multipleTable"
          @selection-change="downTableSelectionChange"
          highlight-current-row
          @current-change="downTableCurrentChange"
          :row-style="{ height: 30 + 'px' }"
        >
          <el-table-column type="selection"> </el-table-column>
          <el-table-column prop="newfield" label="名称" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input v-model="scope.row.newfield" size="small"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="formula" label="表达式" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input v-model="scope.row.formula" size="small"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" show-overflow-tooltip>
            <template slot-scope="scope">
              <!-- <mine-button type="delete" @click="detectRow(scope.row)"
                  >移除</mine-button
                > -->
              <span
                @click="detectDownTableRow(scope.row)"
                class="detect-downTable-row"
                >移除</span
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="button-group__footer">
        <mine-button
          type="primary"
          secondary
          class="button-group__footer__cancel"
          @click="close"
          >取消</mine-button
        >
        <mine-button type="primary" @click="confirm">确定</mine-button>
      </div>
    </div>
  </div>
</template>

<script>
import qs from "qs";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";

export default {
  name: "Attrs",
  props: {
    currentOperatorData: {
      type: Object,
    },
    fileDataList: {
      type: Array,
    },
    currentProcessId: {
      type: String,
    },
  },
  data() {
    return {
      loading: false,
      leftTableData: [],
      rightTableData: this.filterInitData(),
      downTableData: [],
      form: {
        name: "",
        type: "",
      },
      searchInput: "",
      downTableSelectionList: [], // 下列表复选框选中的行
      downTableCurrentRow: {}, // 下列表单机选中的当前行
      isEditFormula: false, // 表达式是否可修改
      downTableTempId: 0, // 下列表每行的临时id
      explainData: {}, // 说明数据
    };
  },
  computed: {
    tableHeight: function () {
      return 0.2 * window.innerHeight + "px";
    },
    downTableHeight: function () {
      return 0.3 * window.innerHeight - 38 + "px";
    },
  },
  methods: {
    filterInitData() {
      let newArr = JSON.parse(JSON.stringify(this.fileDataList));
      newArr = newArr.filter((item) => {
        if (["INTEGER", "FLOAT"].includes(item.type)) {
          return true;
        }
        return false;
      });
      return newArr;
    },
    async getExplainInfo(type) {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/helpInfo/getTree?helpCode=${type}`,
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: {},
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.explainData = result?.data;
            } else {
              _self.$message.warning("获取说明信息失败！");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/helpInfo/getTree?helpCode=${type}`,
          "get",
          "application/json;charset=UTF-8",
          {},
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.explainData = res?.data;
            } else {
              this.$message.warning("获取说明信息失败！");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("getOperatorExplain", type);
        if (res.data.success) {
          this.explainData = res.data?.data;
        } else {
          this.$message.warning("获取说明信息失败！");
        }
      }
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    close() {
      this.$emit("changeFlag");
    },
    async getLeftTable() {
      let params = {
        dirCode: "builtFunction",
      };
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/dictionary/TreeList",
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify(params, { indices: false }),
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.getDownTableData();
              _self.leftTableData = result?.data[0].childrenParams;
            } else {
              _self.$message.error("获取函数数据失败");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/dictionary/TreeList",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(params, { indices: false }),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.getDownTableData();
              this.leftTableData = res?.data[0].childrenParams;
            } else {
              this.$message.error("获取函数数据失败");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("getDicBydirCode", params);
        if (res.data.status === 200) {
          this.getDownTableData();
          this.leftTableData = res.data?.data[0].childrenParams;
        } else {
          this.$message.error("获取函数数据失败");
        }
      }
    },
    // 左边列表当行点击事件
    leftTableRowClick(row) {
      this.downTableData.forEach((item) => {
        if (item.id === this.downTableCurrentRow.id) {
          item.formula = row.optCode + "(" + item.formula + ")";
        }
      });
    },
    // 右边列表当行点击事件
    rightTableRowClick(row) {
      this.downTableTempId++;
      this.downTableData.push({
        formula: row.name,
        id: this.downTableTempId,
      });
    },
    // 确定按钮
    async confirm() {
      this.downTableData = this.downTableData.map((item) => {
        let fieldnameList = item.formula.match(/(?<=\()(.+?)(?=\))/g);
        return Object.assign(item, {
          processingId: this.currentOperatorData.id,
          funsource: "customFunction",
          fieldnames: fieldnameList ? fieldnameList.join(",") : "",
          type: "FLOAT", // 暂时写死
        });
      });
      let params = {
        key: "processingId",
        value: this.currentOperatorData.id,
        t: this.downTableData,
      };

      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/feAttributecreateRule/saveOrUpdateBatchBfClear?key=${params.key}&value=${params.value}`,
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: params.t,
              isStringParam: false,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.$message.success("保存成功");
              _self.close();
            } else {
              _self.$message.error("保存失败");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/feAttributecreateRule/saveOrUpdateBatchBfClear?key=${params.key}&value=${params.value}`,
          "post",
          "application/json;charset=UTF-8",
          params.t,
          false,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.$message.success("保存成功");
              this.close();
            } else {
              this.$message.error("保存失败");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("postAttr", params);
        if (res.status === 200) {
          this.$message.success("保存成功");
          this.close();
        } else {
          this.$message.error("保存失败");
        }
      }
    },
    // 下面的列表复选框选中的行
    downTableSelectionChange(list) {
      this.downTableSelectionList = list;
    },
    // 下列表选中当前行事件
    downTableCurrentChange(row) {
      this.downTableCurrentRow = row;
    },
    // 回显下表格的数据
    async getDownTableData() {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/feAttributecreateRule/list",
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify(
                { processingId: _self.currentOperatorData.id },
                { indices: false }
              ),
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.downTableData = result.data;
              // 将临时id赋值
              _self.downTableTempId =
                result.data[result.data.length - 1].id || 0;
            } else {
              _self.$message.error("获取新属性数据失败");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/feAttributecreateRule/list",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(
            { processingId: this.currentOperatorData.id },
            { indices: false }
          ),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.downTableData = res.data;
              // 将临时id赋值
              this.downTableTempId = res.data[res.data.length - 1].id || 0;
            } else {
              this.$message.error("获取新属性数据失败");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch(
          "getAttributeTableByOperatorId",
          this.currentOperatorData.id
        );
        if (res.data.status === 200) {
          this.downTableData = res.data.data;
          // 将临时id赋值
          this.downTableTempId =
            res.data.data[res.data.data.length - 1]?.id || 0;
        } else {
          this.$message.error("获取新属性数据失败");
        }
      }
    },
    // 删除下列表数据
    detectDownTableRow(row) {
      let findDeleteIndex = this.downTableData.findIndex((item) => {
        if (item.id === row.id) {
          return;
        }
      });
      this.downTableData.splice(findDeleteIndex, 1);
    },
  },
  created() {
    // setTimeout(() => {
    this.getLeftTable();
    // }, 200);
    // setTimeout(() => {
    //   this.getDownTableData();
    // }, 300);
  },
};
</script>
